# Complete deployment script for Dinghong Cloud Screen project
# This script includes validation, build, and deployment steps

$ErrorActionPreference = "Stop"

Write-Host "===============================================" -ForegroundColor Cyan
Write-Host "Dinghong Cloud Screen - Complete Deployment" -ForegroundColor Cyan
Write-Host "===============================================" -ForegroundColor Cyan
Write-Host ""

# Step 1: Validate environment
Write-Host "Step 1: Validating environment..." -ForegroundColor Green

# Check Docker
Write-Host "Checking Docker..." -ForegroundColor Yellow
try {
    $dockerVersion = docker version 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✓ Docker is available" -ForegroundColor Green
    }
    else {
        Write-Host "✗ Docker is not available" -ForegroundColor Red
        exit 1
    }
}
catch {
    Write-Host "✗ Docker is not available" -ForegroundColor Red
    exit 1
}

# Check Minikube
Write-Host "Checking Minikube..." -ForegroundColor Yellow
try {
    $minikubeVersion = minikube version 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✓ Minikube is available" -ForegroundColor Green
    }
    else {
        Write-Host "✗ Minikube is not available" -ForegroundColor Red
        exit 1
    }
}
catch {
    Write-Host "✗ Minikube is not available" -ForegroundColor Red
    exit 1
}

# Check kubectl
Write-Host "Checking kubectl..." -ForegroundColor Yellow
try {
    $kubectlVersion = kubectl version --client 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✓ kubectl is available" -ForegroundColor Green
    }
    else {
        Write-Host "✗ kubectl is not available" -ForegroundColor Red
        exit 1
    }
}
catch {
    Write-Host "✗ kubectl is not available" -ForegroundColor Red
    exit 1
}

# Step 2: Validate project structure
Write-Host "`nStep 2: Validating project structure..." -ForegroundColor Green

# Get project root directory
$PROJECT_ROOT = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path))
Write-Host "Project root: $PROJECT_ROOT" -ForegroundColor Cyan

# Check server directory
$serverPath = Join-Path $PROJECT_ROOT "server"
if (Test-Path $serverPath) {
    Write-Host "✓ Server directory found" -ForegroundColor Green
    if (Test-Path (Join-Path $serverPath "Dockerfile")) {
        Write-Host "✓ Server Dockerfile found" -ForegroundColor Green
    }
    else {
        Write-Host "✗ Server Dockerfile not found" -ForegroundColor Red
        exit 1
    }
}
else {
    Write-Host "✗ Server directory not found" -ForegroundColor Red
    exit 1
}

# Check web directory
$webPath = Join-Path $PROJECT_ROOT "web"
if (Test-Path $webPath) {
    Write-Host "✓ Web directory found" -ForegroundColor Green
    if (Test-Path (Join-Path $webPath "Dockerfile")) {
        Write-Host "✓ Web Dockerfile found" -ForegroundColor Green
    }
    else {
        Write-Host "✗ Web Dockerfile not found" -ForegroundColor Red
        exit 1
    }
}
else {
    Write-Host "✗ Web directory not found" -ForegroundColor Red
    exit 1
}

# Step 3: Build Docker images
Write-Host "`nStep 3: Building Docker images..." -ForegroundColor Green

# Build backend image
Write-Host "Building backend image..." -ForegroundColor Yellow
Set-Location $serverPath
docker build -t dinghong-cloud-screen-server:latest .
if ($LASTEXITCODE -ne 0) {
    Write-Host "✗ Backend image build failed" -ForegroundColor Red
    exit 1
}
Write-Host "✓ Backend image built successfully" -ForegroundColor Green

# Build frontend image
Write-Host "Building frontend image..." -ForegroundColor Yellow
Set-Location $webPath
docker build -t dinghong-cloud-screen-web:latest .
if ($LASTEXITCODE -ne 0) {
    Write-Host "✗ Frontend image build failed" -ForegroundColor Red
    exit 1
}
Write-Host "✓ Frontend image built successfully" -ForegroundColor Green

# Load images to Minikube
Write-Host "Loading images to Minikube..." -ForegroundColor Yellow
minikube image load dinghong-cloud-screen-server:latest
minikube image load dinghong-cloud-screen-web:latest
Write-Host "✓ Images loaded to Minikube" -ForegroundColor Green

# Step 4: Deploy to Minikube
Write-Host "`nStep 4: Deploying to Minikube..." -ForegroundColor Green

# Get script directory
$SCRIPT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Path

# Check Minikube status
$minikubeStatus = minikube status
if ($minikubeStatus -notmatch "Running") {
    Write-Host "Starting Minikube..." -ForegroundColor Yellow
    minikube start --cpus=4 --memory=8192 --disk-size=20g
}
else {
    Write-Host "✓ Minikube is already running" -ForegroundColor Green
}

# Enable Ingress addon
Write-Host "Enabling Ingress addon..." -ForegroundColor Yellow
minikube addons enable ingress

# Wait for Ingress controller to be ready
Write-Host "Waiting for Ingress controller to be ready..." -ForegroundColor Yellow
kubectl wait --namespace ingress-nginx --for=condition=ready pod --selector=app.kubernetes.io/component=controller --timeout=120s

# Apply Kubernetes configurations
Write-Host "Applying Kubernetes configurations..." -ForegroundColor Yellow

# Create namespace
kubectl apply -f "$SCRIPT_DIR\namespace.yaml"

# Deploy database
Write-Host "Deploying MySQL..." -ForegroundColor Yellow
kubectl apply -f "$SCRIPT_DIR\mysql-deployment.yaml"

# Deploy Redis
Write-Host "Deploying Redis..." -ForegroundColor Yellow
kubectl apply -f "$SCRIPT_DIR\redis-deployment.yaml"

# Wait for databases to be ready
Write-Host "Waiting for databases to be ready..." -ForegroundColor Yellow
kubectl wait --namespace dinghong-cloud-screen --for=condition=ready pod --selector=app=gva-mysql --timeout=300s
kubectl wait --namespace dinghong-cloud-screen --for=condition=ready pod --selector=app=gva-redis --timeout=300s

# Deploy backend service
Write-Host "Deploying backend service..." -ForegroundColor Yellow
kubectl apply -f "$SCRIPT_DIR\configmap-server.yaml"
kubectl apply -f "$SCRIPT_DIR\server-deployment.yaml"

# Deploy frontend service
Write-Host "Deploying frontend service..." -ForegroundColor Yellow
kubectl apply -f "$SCRIPT_DIR\nginx-config.yaml"
kubectl apply -f "$SCRIPT_DIR\web-deployment.yaml"

# Deploy Ingress
Write-Host "Deploying Ingress..." -ForegroundColor Yellow
kubectl apply -f "$SCRIPT_DIR\nginx-ingress.yaml"

# Wait for all pods to be ready
Write-Host "Waiting for all services to be ready..." -ForegroundColor Yellow
kubectl wait --namespace dinghong-cloud-screen --for=condition=ready pod --selector=app=gva-server --timeout=300s
kubectl wait --namespace dinghong-cloud-screen --for=condition=ready pod --selector=app=gva-web --timeout=300s

# Get access information
Write-Host "`nStep 5: Getting access information..." -ForegroundColor Green
$MINIKUBE_IP = minikube ip
Write-Host "Minikube IP: $MINIKUBE_IP" -ForegroundColor Cyan

# Add local hosts record
Write-Host "Adding local hosts record..." -ForegroundColor Yellow
$hostsPath = "$env:SystemRoot\System32\drivers\etc\hosts"
$hostsContent = Get-Content $hostsPath -Raw
if ($hostsContent -notmatch "dinghong-cloud-screen\.local") {
    Add-Content -Path $hostsPath -Value "`n$MINIKUBE_IP dinghong-cloud-screen.local" -Force
    Write-Host "✓ Added hosts record: $MINIKUBE_IP dinghong-cloud-screen.local" -ForegroundColor Green
}
else {
    Write-Host "✓ Hosts record already exists" -ForegroundColor Green
}

# Show service status
Write-Host "`nStep 6: Final status check..." -ForegroundColor Green
kubectl get pods -n dinghong-cloud-screen
kubectl get services -n dinghong-cloud-screen
kubectl get ingress -n dinghong-cloud-screen

Write-Host ""
Write-Host "===============================================" -ForegroundColor Green
Write-Host "DEPLOYMENT COMPLETED SUCCESSFULLY!" -ForegroundColor Green
Write-Host "===============================================" -ForegroundColor Green
Write-Host ""
Write-Host "Access URLs:" -ForegroundColor Cyan
Write-Host "• Main Page: http://dinghong-cloud-screen.local" -ForegroundColor White
Write-Host "• API Docs: http://dinghong-cloud-screen.local/api/swagger/index.html" -ForegroundColor White
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "1. Open a new PowerShell window" -ForegroundColor White
Write-Host "2. Run: minikube tunnel" -ForegroundColor White
Write-Host "3. Open your browser and visit the URLs above" -ForegroundColor White
Write-Host ""
Write-Host "Useful commands:" -ForegroundColor Yellow
Write-Host "• View logs: kubectl logs -f deployment/gva-server -n dinghong-cloud-screen" -ForegroundColor White
Write-Host "• Restart services: kubectl rollout restart deployment/gva-server -n dinghong-cloud-screen" -ForegroundColor White
Write-Host "• Clean up: .\cleanup.ps1" -ForegroundColor White 